package com.blog.controller;

import com.blog.pojo.User;
import com.blog.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Controller
@RequestMapping(value = "user", produces = "application/json;charset=utf8")
@ResponseBody
@SuppressWarnings("all")
public class UserController {

    @Autowired()
    private UserService userService;


    Map<String, Object> code = new HashMap<>();

    // user login
    @PostMapping("login")
    public Object login(User user, HttpSession session) {
        // get login user object
        User loginUserObject = userService.login(user);

        if (loginUserObject == null) {
            code.put("code", "1");
            code.put("msg", "账号或密码错误");
            return code;
        }

        // judge user login state is ok
        Integer userState = userService.getUserState(user.getAccount(), user.getPassword());
        if (userState != 1) {
            code.put("code", "1");
            code.put("msg", "您的账号异常,请联系管理员.");
            return code;
        }

        code.put("code", "0");
        code.put("msg", "登录成功");
        code.put("data", loginUserObject);

        // 存储登录用户注册账号必须是您的常用QQ号码,以避免之后更新操作事务.
        session.setAttribute("user", loginUserObject);
        session.setMaxInactiveInterval(30*60);
        return code;
    }


    // get user state
    @RequestMapping("getUserState")
    public Integer getUserState(String account, String password) {
        return userService.getUserState(account, password);
    }


    @PostMapping("register")
    public Object register(User user) {
        // 判断注册用户是否已经注册
        Integer userCount = userService.byUserAccountGetInfo(user.getAccount());

        if (userCount != 0) {
            code.put("code", "1");
            code.put("msg", "注册账号已经存在,");
            return code;
        }

        // 如果注册用户不存在数据库
        boolean register = userService.register(user);
        if (register) {
            code.put("code", "0");
            code.put("msg", "注册成功");
            code.put("data", register);
            return code;
        } else {
            code.put("code", "1");
            code.put("msg", "注册失败,请联系管理员");
            return code;
        }
    }
}
